<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}碳排因子`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="因子名称" prop="factorLabel">
        <el-input v-model="drawerProps.row!.factorLabel" placeholder="请填写因子名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="因子类型" prop="factorName">
        <el-select v-model="drawerProps.row!.factorName" placeholder="请选择因子类型" clearable>
          <el-option v-for="item in factorType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="因子数值" prop="factorValue">
        <el-input v-model="drawerProps.row!.factorValue" placeholder="请填写因子数值" clearable></el-input>
      </el-form-item>
      <el-form-item label="因子单位" prop="factorUnit">
        <el-select v-model="drawerProps.row!.factorUnit" placeholder="请选择因子单位" clearable>
          <el-option v-for="item in unitType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="地域代表性" prop="region">
        <el-select v-model="drawerProps.row!.region" placeholder="请选择地域" clearable>
          <el-option v-for="item in regionType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="数据时间" prop="dataYear">
        <el-date-picker
          v-model="drawerProps.row!.dataYear"
          type="year"
          placeholder="请选择数据时间"
          value-format="YYYY"
          clearable
        />
      </el-form-item> -->
      <el-form-item label="数据来源" prop="source">
        <el-input type="textarea" v-model="drawerProps.row!.source" placeholder="请填写数据来源" clearable :rows="5"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="EmissionFactorDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { EmissionFactor } from "@/api/interface";
import { factorType, unitType, regionType } from "@/utils/serviceDict";
import axios from "axios";
const baseUrl = import.meta.env.VITE_BASE_URL;
const emit = defineEmits(["refresh"]);

const rules = reactive({
  factorId: [{ required: true, message: "请填写因子编号" }], // 碳排因子编号
  factorName: [{ required: true, message: "请选择因子类型" }], // 碳排因子名称
  factorLabel: [{ required: true, message: "请填写因子名称" }], // 碳排因子名称
  factorValue: [{ required: true, message: "请填写因子数值" }], // 所需碳排因子
  factorUnit: [{ required: true, message: "请选择因子单位" }], // 碳排因子描述
  region: [{ required: true, message: "请选择地域" }], // 碳排因子描述
  dataYear: [{ required: true, message: "请填写数据时间" }], // 添加数据时间的验证规则
  source: [{ required: true, message: "请填写数据来源" }] // 碳排因子描述
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<EmissionFactor.ResEmissionFactor>;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，因此需要加1
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      //后端启用调用新增或编辑方法
      // await drawerProps.value.api!(drawerProps.value.row);
      //静态数组新增数据
      if (drawerProps.value.title === "新增") {
        drawerProps.value.row.createTime = formatDate(new Date());
        const response = await axios.post(baseUrl + "/api/carbon/createFactor", {
          factorLabel: drawerProps.value.row.factorLabel,
          factorName: Number(drawerProps.value.row.factorName),
          factorValue: Number(drawerProps.value.row.factorValue),
          region: Number(drawerProps.value.row.region),
          factorUnit: String(drawerProps.value.row.factorUnit),
          source: drawerProps.value.row.source,
          createTime: drawerProps.value.row.createTime
        });
        if (response.data && response.data.code === 200) {
          ElMessage.success("新增碳排因子成功！");
          emit("refresh"); // 通知父组件刷新
        } else {
          ElMessage.error(response.data.msg || "新增碳排因子失败");
        }
      }
      //静态数组编辑数据
      else if (drawerProps.value.title === "编辑") {
        console.log("编辑碳排因子信息:", drawerProps.value.row);
        const response = await axios.post(baseUrl + "/api/carbon/updateFactor", {
          id: drawerProps.value.row.id,
          factorLabel: drawerProps.value.row.factorLabel,
          factorName: Number(drawerProps.value.row.factorName),
          factorValue: Number(drawerProps.value.row.factorValue),
          region: Number(drawerProps.value.row.region),
          factorUnit: String(drawerProps.value.row.factorUnit),
          source: drawerProps.value.row.source,
        });
        if (response.data && response.data.code === 200) {
          ElMessage.success("编辑碳排因子信息成功！");
          emit("refresh"); // 通知父组件刷新
        } else {
          ElMessage.error(response.data.msg || "修改碳排因子信息失败");
        }
      }
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
